<?php

class Auth extends BaseController
{
    /**
     * 用户登录接口
     */
    public function login()
    {
        if (request()->isPost()) {
            $param = get_params();
            $username = $param['username'] ?? '';
            $password = $param['password'] ?? '';
            
            // 验证参数
            if (empty($username) || empty($password)) {
                return $this->apiError('用户名和密码不能为空');
            }
            
            // 查询用户
            $user = Db::name('admin')->where(['username' => $username])->find();
            if (empty($user)) {
                return $this->apiError('用户不存在');
            }
            
            // 验证密码
            if (md5($password . $user['salt']) !== $user['password']) {
                return $this->apiError('密码错误');
            }
            
            // 检查用户状态
            if ($user['status'] != 1) {
                return $this->apiError('用户已被禁用');
            }
            
            // 生成token (简化实现，实际项目中应使用JWT)
            $token = md5($user['id'] . $user['username'] . time());
            
            // 保存登录状态
            $session_admin = get_config('app.session_admin');
            Session::set($session_admin, $user['id']);
            
            // 返回用户信息和token
            $userInfo = [
                'id' => $user['id'],
                'username' => $user['username'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar'] ?: '/static/admin/images/avatar.png'
            ];
            
            $data = [
                'token' => $token,
                'userInfo' => $userInfo
            ];
            
            return $this->apiSuccess('登录成功', $data);
        }
        
        return $this->apiError('请求方式错误');
    }
}